<template>
	<view class="container">
		<view class="room-list">
			<view v-for="(room, index) in rooms" :key="index" class="room-item">
				<!-- 房间信息 -->
				<view class="room-info">
					<view class="info-row">
						<text class="label">房间名称：</text>
						<text class="value">{{ room.name }}</text>
					</view>
					<view class="info-row">
						<text class="label">起订时长：</text>
						<text class="value">{{ room.duration }}分钟</text>
					</view>
					<view class="info-row">
						<text class="label">赛道名称：</text>
						<text class="value">{{ room.area[0][0].name }}</text>
					</view>
				</view>
				<!-- 操作按钮 -->
				<view class="room-actions">
					<text class="action red" @click="deleteRoom(index, room.id)">删除房间</text>
					<view class="separator"></view>
					<text class="action" @click="editRoom(room)">编辑房间</text>
					<view class="separator"></view>
					<text class="action" @click="showQRCode(room)">显示二维码</text>
				</view>

			</view>
		</view>
		<view>
			<button class="add-room-button" @click="addRoom">添加房间</button>
		</view>

		<view v-if="isQRCodeVisible" class="qrcode-popup">
			<view class="popup-container">
				<view class="popup-header">
					<text class="popup-title">房间二维码</text>
					<text class="popup-close" @click="isQRCodeVisible = false">关闭</text>
				</view>

				<!-- 显示二维码 -->
				<!-- <image :src="'https://wq.hoeagri.com' + currentQRCode" class="qrcode-image" mode="aspectFit" /> -->
				<image :src="$xyfun.image(currentQRCode)" class="qrcode-image" mode="aspectFit" />
				<!-- 点击保存到本地按钮 -->
				<view class="save-button-container">
					<button class="save-button" @click="prepareQRCodeImage">保存到本地</button>
				</view>

				<view class="popup-footer">
					<text class="footer-text">点击按钮保存二维码</text>
				</view>
			</view>
		</view>
		<!-- 传递 currentRoom 到 RoomAdd 子组件 -->
		<room-add :show="isTimeVisible" :roomData="currentRoom" @close="closeRoom"
			@refreshData="handleRefreshData"></room-add>
	</view>
</template>

<script>
	import RoomAdd from './components/RoomAdd.vue';

	export default {
		components: {
			RoomAdd
		},
		data() {
			return {
				// roomId: 0,
				isTimeVisible: false,
				rooms: [], // 初始化为空数组
				currentRoom: {}, // 确保 currentRoom 初始化为一个空对象
				currentQRCode: '', // 存储当前房间的二维码路径
				isQRCodeVisible: false, // 控制二维码显示的状态
			};
		},
		onShow() {
			this.$xyfun.setNavBg();
			this.css = this.$xyfun.css();
			this.loadRoom();
			// 请求保存相册权限
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success() {
					console.log('用户授权了相册权限');
				},
				fail() {
					console.log('用户未授权相册权限');
					uni.showToast({
						title: '请授权相册权限',
						icon: 'none',
						duration: 2000
					});
				}
			});
		},
		methods: {
			// saveQRCode() {
			// 	// 获取二维码图片的完整URL
			// 	const imageUrl = 'https://wq.hoeagri.com' + this.currentQRCode;

			// 	// 调用微信小程序API保存图片到相册
			// 	wx.saveImageToPhotosAlbum({
			// 		filePath: imageUrl,
			// 		success(res) {
			// 			// 图片保存成功后，提示用户
			// 			uni.showToast({
			// 				title: '图片已保存',
			// 				icon: 'success',
			// 				duration: 2000
			// 			});
			// 		},
			// 		fail(err) {
			// 			// 处理失败情况，例如没有授权等
			// 			uni.showToast({
			// 				title: '保存失败，请重试',
			// 				icon: 'none',
			// 				duration: 2000
			// 			});
			// 			console.error('保存失败', err);
			// 		}
			// 	});
			// },
			loadRoom() {
				this.$xyfun.userStoreId().then((store_id) => {
					this.$api.post({
						url: '/Venue/Listvenue',
						loadingTip: '加载中...',
						data: {
							store_id: store_id,
						},
						success: res => {
							uni.stopPullDownRefresh();
							this.isLoading = false;
							// 打印返回数据，用于调试
							// console.log('接口返回的数据hh:', res);
							this.rooms = res.rooms; // 更新 rooms 数据
						},
						fail: () => {
							uni.stopPullDownRefresh();
							this.isLoading = false;
							this.rooms = []; // 请求失败时清空房间数据
							console.error('接口请求失败');
						}
					});
				});
			},
			deleteRoom(index, id) {
				// 弹出确认对话框
				uni.showModal({
					title: '删除房间',
					content: '确认删除此房间吗？',
					success: (res) => {
						if (res.confirm) {
							// 用户点击确认
							this.rooms.splice(index, 1); // 在前端移除房间
							this.$xyfun.userStoreId().then((store_id) => {
								this.$api.post({
									url: '/Venue/Delvenue',
									loadingTip: '加载中...',
									data: {
										id: id,
									},
									success: res => {
										uni.stopPullDownRefresh();
										this.isLoading = false;
										this.loadRoom(); // 删除后重新加载房间列表
									}
								});
							});
						} else if (res.cancel) {
							// 用户点击取消
							console.log('用户取消删除');
						}
					}
				});
			},

			// 处理刷新数据的逻辑
			handleRefreshData() {
				this.loadRoom();
			},
			editRoom(room) {
				console.log('Selected room:', room); // 输出房间数据
				// 编辑房间时设置 currentRoom 为选中的房间
				this.currentRoom = {
					...room
				}; // 确保复制一份，不影响原数据
				// console.log('Selected currentRoom:', this.currentRoom); // 输出房间数据
				this.isTimeVisible = true; // 确保在 currentRoom 更新后显示弹窗
			},

			addRoom() {
				// 添加房间时清空 currentRoom
				this.currentRoom = {}; // 使用空对象而不是 null
				this.isTimeVisible = true; // 确保在 currentRoom 更新后显示弹窗
			},
			closeRoom() {
				this.isTimeVisible = false; // 隐藏弹窗
			},
			showQRCode(room) {
				console.log("hhaha ");

				this.currentQRCode = room.qrcode; // 获取二维码路径
				console.log('https://wq.hoeagri.com' + this.currentQRCode);
				this.isQRCodeVisible = true; // 显示二维码

				// 让图片支持长按保存功能
				// this.prepareQRCodeImage();
			},
			// 下载并保存二维码图片到相册
			prepareQRCodeImage() {
				// 下载图片到本地临时文件
				wx.downloadFile({
					url: 'https://wq.hoeagri.com' + this.currentQRCode, // 使用网络图片的 URL
					success: (res) => {
						if (res.statusCode === 200) {
							const tempFilePath = res.tempFilePath; // 获取下载后的临时文件路径
							this.saveImageToAlbum(tempFilePath);
						} else {
							uni.showToast({
								title: '图片下载失败',
								icon: 'none',
								duration: 2000
							});
						}
					},
					fail: (err) => {
						console.error('下载图片失败', err);
						uni.showToast({
							title: '下载图片失败',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},

			// 保存图片到相册
			saveImageToAlbum(tempFilePath) {
				wx.saveImageToPhotosAlbum({
					filePath: tempFilePath,
					success: () => {
						uni.showToast({
							title: '图片已保存',
							icon: 'success',
							duration: 2000
						});
					},
					fail: (err) => {
						uni.showToast({
							title: '保存失败，请重试',
							icon: 'none',
							duration: 2000
						});
						console.error('保存失败', err);
					}
				});
			}

		}
	};
</script>

<style scoped>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		padding-bottom: 150rpx;
		height: 100vh;
		/* 为固定按钮预留空间 */
	}

	.header {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx 0;
		background-color: #fff;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.room-list {
		margin-top: 30rpx;
		padding-bottom: 115rpx; /* 留出空间给固定的添加按钮 */
	}

	.room-item {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: stretch;
		padding: 20rpx;
		border: 1px solid #eee;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		background-color: #fff;
	}

	.room-info {
		display: flex;
		flex-direction: column;
		margin-bottom: 10rpx;
		width: 100%;
	}

	.info-row {
		display: flex;
		justify-content: space-between;
		/* 让 label 和 value 左右对齐 */
		align-items: center;
		/* 垂直居中 */
		margin-bottom: 10rpx;
	}

	.label {
		font-size: 28rpx;
		color: #000;
		flex: 1;
		/* label 占据剩余空间 */
	}

	.value {
		font-size: 28rpx;
		color: #000;
		text-align: right;
		/* value 靠右对齐 */
	}

	.room-actions {
		display: flex;
		justify-content: space-between;
		/* 两端对齐 */
		align-items: center;
		width: 100%;
		/* 确保容器占满宽度 */
	}

	.action {
		font-size: 28rpx;
		color: #000000;
		cursor: pointer;
		font-weight: bold;
		/* padding: 0 40px; 不需要这个，改用适当的 margin 或者缩小字体间距 */
		margin: 0 10px;
		/* 增加左右间距，避免按钮之间太近 */
	}


	.red {
		color: #FF0000;
	}

	.separator {
		width: 1px;
		height: 28rpx;
		background-color: #ccc;
		margin: 0 10rpx;
	}

	/* 添加房间按钮固定在底部 */
	.add-room-button {
		position: fixed;
		bottom: 20rpx;
		left: 20rpx;
		right: 20rpx;
		height: 95rpx;
		line-height: 95rpx;
		background-color: #65C61D;
		color: #fff;
		border: none;
		border-radius: 20rpx;
		font-size: 32rpx;
		cursor: pointer;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
	}

	.add-room-button:hover {
		background-color: #45a049;
	}

	.qrcode-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		/* 半透明背景 */
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	.popup-container {
		background-color: #fff;
		/* 弹窗背景 */
		width: 80%;
		/* 弹窗宽度占屏幕的80% */
		max-width: 350px;
		/* 限制最大宽度 */
		padding: 20rpx;
		border-radius: 12rpx;
		/* 弹窗圆角 */
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.popup-header {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1px solid #ccc;
	}

	.popup-title {
		font-size: 32rpx;
		color: #333;
	}

	.popup-close {
		font-size: 30rpx;
		color: #FF0000;
		cursor: pointer;
	}

	.qrcode-image {
		width: 100%;
		/* 容器宽度的100% */
		/* height: 100%; 容器高度的100% */
		/* object-fit: contain; 确保图片自适应且不变形 */
		margin: 20rpx 0;
		/* 上下间距 */
	}


	.popup-footer {
		margin-top: 20rpx;
		text-align: center;
	}

	.footer-text {
		font-size: 24rpx;
		color: #666;
	}
	
	.save-button-container {
	  margin-top: 20rpx;
	  text-align: center;
	}
	
	.save-button {
	  background-color: #65C61D;
	  color: #fff;
	  border: none;
	  padding: 12rpx 25rpx;  /* 调整按钮的内边距 */
	  font-size: 24rpx;  /* 设置字体大小为 24rpx */
	  border-radius: 8rpx;
	  cursor: pointer;
	}
	
	.save-button:hover {
	  background-color: #45a049;
	}

</style>